package com.jy.api.controller.member;

import com.jy.api.dao.MemberAccountDao;
import com.jy.api.dao.MemberDao;
import com.jy.api.dao.StoreDao;
import com.jy.api.dao.TeamTransactionDao;
import com.jy.api.domain.Member;
import com.jy.api.domain.MemberAccount;
import com.jy.api.domain.Store;
import com.jy.api.domain.TeamTransaction;
import com.jy.api.exception.MyException;
import com.jy.api.service.MemberAccountService;
import com.jy.api.service.StoreService;
import com.jy.api.signUpReq.member.MemberStoreSignUpReq;
import com.jy.api.util.OpenSearchUtil;
import com.jy.api.vo.member.OpenSearchMemberVo;
import com.jy.api.vo.pos.member.MemberVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by lihu on 2017/11/22.
 */
@Slf4j
@RestController
@RequestMapping(value = "/v1/member", produces = "application/json;charset=utf-8")
public class MerberStoreController {


    @Autowired
    MemberDao memberDao;

    @Autowired
    StoreService storeService;


    @Autowired
    MemberAccountService memberAccountService;


    @Autowired
    private TeamTransactionDao teamTransactionDao;

    /**
     * 查询店铺信息
     *
     * @param openid
     * @param q
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/{openid}/stores")
    public ResponseEntity queryMemberStores(@PathVariable String openid,
                                            @RequestParam(name = "q", defaultValue = "") String q) {
        try {
            Member member = memberDao.findByOpenId(openid);
            if (member == null) {
                return new ResponseEntity("你不是店铺会员！请先成为会员！", HttpStatus.BAD_REQUEST);
            }
            return new ResponseEntity(storeService.getMemberStoreLike(member.getId(), q), HttpStatus.OK);
        } catch (Exception ex) {
            log.error("queryMemberStores is error==> openid:{},q:{}", openid, q, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 查询所有店铺信息
     *
     * @param q
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    public ResponseEntity getAllStore(@RequestParam(name = "q", defaultValue = "") String q) {
        try {
            return new ResponseEntity(storeService.getMemberAllStoreLike(q), HttpStatus.OK);
        } catch (Exception ex) {
            log.error("queryMemberStores is error==> q:{}", q, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 获取会员对应店铺信息
     *
     * @param openid
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/{openid}/stores-info")
    public ResponseEntity queryMemberStoresInfo(@PathVariable String openid,
                                                @PageableDefault(value = 10, sort = {"addTime"}, direction = Sort.Direction.DESC) Pageable pageable) {
        try {
            Object memberId = memberDao.checkMember(openid);
            if (memberId == null) {
                memberId = memberDao.findOne(openid);
            }
            if (memberId == null) {
                return new ResponseEntity("你不是店铺会员！请先成为会员！", HttpStatus.BAD_REQUEST);
            }
            return new ResponseEntity(storeService.getStoreIndo(memberId.toString(), pageable), HttpStatus.OK);
        } catch (Exception ex) {
            log.error("queryMemberStoresInfo is error==> openid:{}", openid, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 会员添加店铺（主动关联店铺）
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/add-store")
    public ResponseEntity addMember(@Valid @RequestBody MemberStoreSignUpReq memberStoreSignUpReq,
                                    BindingResult bindingResult) {
        try {
            if (bindingResult.hasErrors()) {
                log.error("【添加店铺会员】参数不正确, memberStoreSignUpReq={}", memberStoreSignUpReq);
                return new ResponseEntity(bindingResult.getFieldError().getDefaultMessage(), HttpStatus.BAD_REQUEST);
            }
            memberAccountService.memberAddStore(memberStoreSignUpReq);
            return ResponseEntity.ok("");
        } catch (MyException ex) {
            log.error("addMember is error==> memberStoreSignUpReq:{}", memberStoreSignUpReq, ex);
            return new ResponseEntity(ex.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (Exception ex) {
            log.error("addMember is error==> memberStoreSignUpReq:{}", memberStoreSignUpReq, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }


    /**
     * 会员搜索：只支持手机号
     *
     * @param storeId
     * @param q
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/members-search")
    public ResponseEntity queryProduct(@RequestParam(name = "storeId") String storeId,
                                       @RequestParam(name = "q", defaultValue = "") String q) {
        try {
            List<MemberVo> memberVos = new ArrayList<>();
            List<Object[]> objects = memberDao.getMember(storeId, q);
            for (Object[] o : objects) {
                MemberVo memberVo = new MemberVo(o[0].toString(), o[1].toString(),
                        o[2] != null ? o[2].toString() : "", o[3].toString(),
                        Double.parseDouble(o[4].toString()),
                        o[5].toString());
                memberVos.add(memberVo);
            }
            TeamTransaction teamTransaction = teamTransactionDao.findByStoreIdAndEnable(storeId, true);
            if (teamTransaction != null) {
                objects = memberDao.getMemberTeam(teamTransaction.getTeamId(), q);
                for (Object[] o : objects) {
                    MemberVo memberVo = new MemberVo(o[0].toString(), o[1].toString(),
                            o[2] != null ? o[2].toString() : "", o[3].toString(),
                            Double.parseDouble(o[4].toString()),
                            o[5].toString());
                    memberVos.add(memberVo);
                }
            }
            return new ResponseEntity(memberVos, HttpStatus.OK);
        } catch (Exception ex) {
            log.error("queryMember is error==> storeId:{},q:{}", storeId, q, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
